package com.zheng.hr.rpc.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.zheng.common.annotation.BaseService;

import com.zheng.common.entity.WeixinUser;
import com.zheng.common.util.PinYinUtils;
import com.zheng.common.util.WeixinUtil;
import com.zheng.hr.dao.model.HrPersonalExperience;
import com.zheng.hr.dao.model.HrPersonalRecords;
import com.zheng.hr.dao.mapper.HrPersonalRecordsMapper;
import com.zheng.hr.rpc.api.HrDictService;
import com.zheng.hr.rpc.api.HrPersonalExperienceService;
import com.zheng.hr.rpc.api.HrPersonalRecordsService;
import com.zheng.common.base.BaseServiceImpl;
import com.zheng.oa.common.exception.OaException;
import com.zheng.upms.dao.model.UpmsOrganization;
import com.zheng.upms.dao.model.UpmsUser;
import com.zheng.upms.rpc.api.UpmsOrganizationService;
import com.zheng.upms.rpc.api.UpmsUserService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * hr_personal_records 人事档案信息 服务实现类
 * </p>
 *
 * @author likun
 * @since 2018-01-08
 */
@Service
@Transactional(rollbackFor = Exception.class)
@BaseService
public class HrPersonalRecordsServiceImpl extends BaseServiceImpl<HrPersonalRecordsMapper, HrPersonalRecords> implements HrPersonalRecordsService {
    @Autowired
    private UpmsUserService upmsUserService;
    @Autowired
    private HrPersonalExperienceService personalExperienceService;
    @Autowired
    private HrDictService dictService;
    @Autowired
    private UpmsOrganizationService organizationService;

    @Override
    public boolean insertPersonalRecords(HrPersonalRecords personalRecords, List<HrPersonalExperience> experiences) throws OaException {
        //todo 工号 手机号 需要修改
        String ename = PinYinUtils.toPinyin(personalRecords.getRealname());
        String jobNumber = personalRecords.getJobNumber();
        String phone = personalRecords.getPhone();
        EntityWrapper<HrPersonalRecords> personalRecordsEntityWrapper = new EntityWrapper<>();
        personalRecordsEntityWrapper.eq("job_number", jobNumber);
        if (selectCount(personalRecordsEntityWrapper) > 0) {
            throw new OaException("已添加该工号，请更换工号！");
        }
        personalRecordsEntityWrapper = new EntityWrapper<>();
        personalRecordsEntityWrapper.eq("phone", phone);
        if (selectCount(personalRecordsEntityWrapper) > 0) {
            throw new OaException("该手机号已被其他用户注册！");
        }
        UpmsUser user = new UpmsUser();
        //使用手机号当做登录账号
        user.setUsername(phone);
        user.setLocked(0);
        user.setCtime(new Date());
        user.setRealname(personalRecords.getRealname());
        user.setOrganizationId(personalRecords.getOrganizationId());
        user.setRealUser(UpmsUser.IS_REAL_USER);
        user = upmsUserService.createUser(user);
        if (null == user) {
            throw new OaException("添加账户失败！");
        }
        personalRecords.setUserId(user.getUserId());
        personalRecords.setEname(ename);
        personalRecords.setCtime(new Date());
        //设定在职
        personalRecords.setInservice(true);
        //如果没有设定部门，就设定在根目录下
        if (personalRecords.getOrganizationId() == null) {
            UpmsOrganization organization = organizationService.selectList(null).get(0);
            personalRecords.setOrganizationId(organization.getOrganizationId());
        }
        insert(personalRecords);
        for (HrPersonalExperience experience : experiences) {
            experience.setPersonalId(personalRecords.getId());
            if (!personalExperienceService.insert(experience)) {
                throw new OaException("添加工作经历失败！");
            }
        }
        return WeixinUtil.insertUser(getWeixinUser(personalRecords));
    }

    private WeixinUser getWeixinUser(HrPersonalRecords personalRecords) {
        WeixinUser weixinUser = new WeixinUser();
        weixinUser.setName(personalRecords.getRealname());
        List<Integer> organizationIds = new ArrayList<>();
        organizationIds.add(personalRecords.getOrganizationId());
        weixinUser.setDepartment(organizationIds);
        weixinUser.setGender(personalRecords.getGender());
        weixinUser.setMobile(personalRecords.getPhone());
        weixinUser.setUserid(personalRecords.getPhone());
        return weixinUser;
    }

    @Override
    public boolean updatePersonalRecords(HrPersonalRecords personalRecords, List<HrPersonalExperience> experiences) throws OaException {
        EntityWrapper<HrPersonalExperience> experienceEntityWrapper = new EntityWrapper<>();
        experienceEntityWrapper.where("personal_id=" + personalRecords.getId());
        if (!personalExperienceService.delete(experienceEntityWrapper)) {
            throw new OaException("操作失败！");
        }
        for (HrPersonalExperience experience : experiences) {
            experience.setPersonalId(personalRecords.getId());
            if (!personalExperienceService.insert(experience)) {
                throw new OaException("添加工作经历失败！");
            }
        }
        Integer userId = selectById(personalRecords).getUserId();
        UpmsUser upmsUser = new UpmsUser();
        upmsUser.setUserId(userId);
        upmsUser.setRealname(personalRecords.getRealname());
        upmsUserService.updateById(upmsUser);
        personalRecords.setPositionId(null);
        personalRecords.setOrganizationId(null);
        updateById(personalRecords);
        return WeixinUtil.updateUser(getWeixinUser(personalRecords));
    }

    @Override
    public List<Map<String, Object>> selectPersonalRecordsPage(HrPersonalRecords personalRecords) {
        return baseMapper.selectPersonalRecordsPage(personalRecords);
    }

    @Override
    public Integer selectPersonalRecordsCount(HrPersonalRecords personalRecords) {
        return baseMapper.selectPersonalRecordsCount(personalRecords);
    }

    @Override
    public List<Map<String, Object>> selectPersonalRecordsMaps(HrPersonalRecords personalRecords) {

        return baseMapper.selectPersonalRecordsMaps(personalRecords);
    }

    public List<Map<String, Object>> personalRecordsMapsTransformation(List<Map<String, Object>> maps) {
        for (Map<String, Object> map : maps) {
            Object gender = map.get("gender");
            if (null != gender) {
                map.put("gender", dictService.getDictName(gender.toString(), "gender", null));
            }
            Object education = map.get("education");
            if (null != education) {
                map.put("education", dictService.getDictName(education.toString(), "education", null));
            }
            Object educationType = map.get("educationType");
            if (null != educationType) {
                map.put("educationType", dictService.getDictName(educationType.toString(), "education_type", null));
            }
            Object parttimeType = map.get("parttimeType");
            if (null != parttimeType) {
                map.put("parttimeType", dictService.getDictName(parttimeType.toString(), "parttime_type", null));
            }
            Object political = map.get("political");
            if (null != political) {
                map.put("political", dictService.getDictName(political.toString(), "political", null));
            }
            Object inservice = map.get("inservice");
            if (null != inservice) {
                if (inservice == "true") {
                    map.put("inservice", "是");
                } else {
                    map.put("inservice", "否");
                }
            }
            Object signed = map.get("signed");
            if (null != signed) {
                if (signed == "true") {
                    map.put("signed", "是");
                } else {
                    map.put("signed", "否");
                }
            }
            Object probation = map.get("probation");
            if (null != probation) {
                if (probation == "true") {
                    map.put("probation", "是");
                } else {
                    map.put("probation", "否");
                }
            }
            Object parttime = map.get("parttime");
            if (null != parttime) {
                if (parttime == "true") {
                    map.put("parttime", "是");
                } else {
                    map.put("parttime", "否");
                }
            }
        }
        return maps;
    }

    public List<Map<String, Object>> selectAllUsersName() {
        return baseMapper.selectAllUsersName();
    }

    public Map<String, Object> getPersonalRecordsInfo(Integer userId) {
        return baseMapper.getPersonalRecordsInfo(userId);
    }

    @Override
    public boolean insertUserList(List<UpmsUser> users) {
        boolean result = false;
        for (UpmsUser upmsUser : users) {
            upmsUser = upmsUserService.createUser(upmsUser);
            HrPersonalRecords personalRecords = new HrPersonalRecords();
            personalRecords.setCtime(new Date());
            if (null == upmsUser) {
                continue;
            }
            personalRecords.setUserId(upmsUser.getUserId());
            personalRecords.setAvatar(upmsUser.getAvatar());
            personalRecords.setOrganizationId(upmsUser.getOrganizationId());
//            personalRecords.setEname(upmsUser.getString("english_name"));
            personalRecords.setInservice(true);
            personalRecords.setRealname(upmsUser.getRealname());
            personalRecords.setPhone(upmsUser.getPhone());
            result = insert(personalRecords);
        }
        return result;
    }
}
